import React from "react";
import { connect } from 'react-redux'
import { Checkbox, Row, Col, Button, message, Form, Select, Switch, Input, Modal} from 'antd'
const Option = Select.Option;
const {TextArea} = Input;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
import 'styles/help-center-admin/question-maintenance-edit.scss'
import QuestionMaintenanceService from 'containers/help-center-admin/question-maintenance/question-maintenance-service'
import {deepCopy, messages } from "share/common";
import menuRoute from "routes/menuRoute";
import TitleAndContentI18n from 'components/template/title-and-content-i18n/title-and-content-i18n'

class QuestionMaintenanceEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      disabled: false,
      record: {
        id: null,
        i18n: {question: [], answer: []},
        enabled: true,
        public: true,
        commonProblemCategoryId: null,
        authorities: [],
        remark: '',
      },
      i18n: {title: [], content: []},
      authorities: [],//选中的角色
      authorityOption: [],//角色选项
      categoryList: [],
      categoryId: '',//当前问题所属分类ID
      id: this.props.location.state.id,//问题ID
      hisId: this.props.location.state.hisId,//版本ID
      index: this.props.location.state.index,//index标记着当前版本是否为最新版本，index为0则为最新版本
      quesMain: menuRoute.getRouteItem('question-maintenance', 'key').url,
      detailQues: menuRoute.getRouteItem('question-maintenance-detail', 'key').url,
    }
  }

  componentWillMount (){
    if(this.state.hisId){
      this.getHistoryDetail()
    }else{
      if(this.state.id){
        this.getQuesDetail()
      }
    }
    this.getAuthorityList();
    this.getCategoryList();
  }

  getQuesDetail = () => {
    const {i18n} = this.state;
    this.setState({
      loading: true,
    });
    QuestionMaintenanceService.getQuesDetail(this.state.id, this.props.language.code).then(res => {
      let arr = [];
      if(res.data.authorities){
        res.data.authorities.map(item => {
          arr.push(item.code)
        });
      }
      if(res.data.i18n){
        i18n.title = res.data.i18n.question;
        i18n.content = res.data.i18n.answer;
      }
      this.setState({
        record: res.data,
        categoryId: res.data.commonProblemCategoryId,
        loading: false,
        i18n: deepCopy(i18n),
        authorities: arr,
        disabled: (res.data.tenantId === 0 || res.data.tenantId === "0"),
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };


  //获取历史版本详情
  getHistoryDetail = () => {
    this.setState({
      loading: true,
    });
    const {i18n} = this.state;
    QuestionMaintenanceService.getHistoryDetail(this.state.hisId, this.props.language.code).then(res => {
      let arr = [];
      if(res.data.authorities){
        res.data.authorities.map(item => {
          arr.push(item.code)
        });
      }
      if(res.data.tenantId === 0 || res.data.tenantId === "0"){
        this.setState({
          disabled: true,
        });
      }
      if(res.data.i18n){
        i18n.title = res.data.i18n.question;
        i18n.content = res.data.i18n.answer;
      }
      this.setState({
        record: res.data,
        loading: false,
        authorities: arr,
        i18n: deepCopy(i18n),
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  getAuthorityList = () => {
    this.setState({
      loading: true,
    });
    QuestionMaintenanceService.getAuthorityList().then(res => {
      res.data.map(item => {
        item.label = item.name;
        item.value = item.code;
      });
      this.setState({
        authorityOption: res.data,
        loading: false,
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    });
  };

  //获取问题分类列表
  getCategoryList = () => {
    this.setState({
      loading: true,
    });
    QuestionMaintenanceService.getCategoryList('COMMONPROBLEM', this.props.language.code).then(res => {
      this.setState({
        loading: false,
        categoryList: res.data,
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  handleSave = () => {
    const {index, hisId} = this.state;
    if(hisId){
      if(index === 0){
        this.saveDetail();
      }else{
        Modal.confirm({
          title: messages('help-center-admin.key10')/*保存后，该版本会覆盖之前的内容成为最新版本，您要继续您的操作么？*/,
          onOk: () => {
            this.saveDetail();
          }
        })
      }
    }else{
      this.saveDetail();
    }
  };

  saveDetail = () => {
    const { record, authorities, detailQues, authorityOption, disabled} = this.state;
    let err = false;
    record.i18n.question.map(item => {
      if(item.value.length > 200){
        err = true;
      }
    });
    if(err){
      message.error(messages('help-center-admin.key11')/*名称长度不能超过200个字符*/)
    }else {
      let err2 = true;
      record.i18n.question.map(item => {
        if(item.value){
          if(record.i18n.answer.filter(ans => ans.language === item.language)[0].value.length > 7){
            err2 = false;
          }
        }
        if(item.language.toLowerCase() === this.props.language.code.toLowerCase()){
          record.question = item.value;
          record.answer = record.i18n.answer.filter(ans => ans.language === item.language)[0].value
        }
      });
      if(err2){
        message.error(messages('help-center-admin.key38')/*请至少填写一种语言的标题和正文*/);
      }else {
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            let arr = [];
            let params = {};
            this.setState({
              loading: true,
            });
            if(disabled){
              params = record;
              params.enabled = values.enabled;
            }else {
              params = Object.assign(JSON.parse(JSON.stringify(record)), values);
            }
            authorityOption.map(item => {
              if (authorities.indexOf(item.code) !== -1) {
                arr.push({id: item.id, name: item.name, code: item.code});
              }
            });
            params.authorities = arr;
            if (this.state.id || this.state.hisId) {
              if (this.state.hisId) {
                params.id = params.sourceId;
              }
              QuestionMaintenanceService.editQues(params).then(res => {
                this.setState({
                  loading: false,
                });
                message.success(messages('help-center-admin.key12')/*保存成功*/);
                this.context.router.push({
                  pathname: detailQues,
                  state: {
                    categoryId: res.data.commonProblemCategoryId,
                    questionId: res.data.id,
                  }
                });
              }).catch(err => {
                this.setState({
                  loading: false,
                });
              });
            } else {
              QuestionMaintenanceService.addQues(params).then(res => {
                this.setState({
                  loading: false,
                });
                message.success(messages('help-center-admin.key12')/*保存成功*/);
                this.context.router.push({
                  pathname: detailQues,
                  state: {
                    categoryId: res.data.commonProblemCategoryId,
                    questionId: res.data.id,
                  }
                });
              }).catch(err => {
                this.setState({
                  loading: false,
                });
              });
            }

          }
        })
      }
    }
  };

  onAuthorityNamesChange = (value) => {
    let authorities = this.state.authorities;
    let valueIsChecked = authorities.length < value.length;
    let modifyValue = '';
    (authorities.length < value.length ? value : authorities).map(code => {
      if ((authorities.length < value.length ? authorities : value).indexOf(code) === -1)
        modifyValue = code
    });
    this.setState({ authorities: value });
    if (valueIsChecked && modifyValue === 'ROLE_USER') { //若选中员工，则财务及管理员都被选中
      this.setState({ authorities: ['ROLE_USER', 'ROLE_COMPANY_FINANCE_ADMIN', 'ROLE_COMPANY_ADMIN', 'ROLE_TENANT_ADMIN'] })
    }
    if (!valueIsChecked && modifyValue !== 'ROLE_USER' && value.indexOf('ROLE_USER') !== -1) { //若取消选中非"全员"的选项，则"全员"也要取消选中
      value.delete('ROLE_USER');
      this.setState({ authorities: value })
    }
  };

  goBack = () => {
    const {categoryId, id, detailQues, quesMain} = this.state;
    if(id){
      this.context.router.push({
        pathname: detailQues,
        state: {
          categoryId,
          questionId: id,
        }
      });
    }else{
      this.context.router.push({
        pathname: quesMain,
        state: {}
      });
    }
  };

  onI18nChange = (i18n) => {
    const {record} = this.state;
    record.i18n.question = i18n.title;
    record.i18n.answer = i18n.content;
    this.setState({ record })

  };

  render() {
    const {record, authorities, authorityOption, categoryList, loading, disabled, i18n} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 9},
    };
    return (
      <div className={'question-maintenance-edit'}>
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('enabled', {
              initialValue: record.enabled,
              valuePropName: 'checked',
              rules: [{
                required: false,
              }]
            })
            (<Switch/>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label={messages('help-center-admin.key4')/*分类*/}>
            {getFieldDecorator('commonProblemCategoryId', {
              initialValue: disabled ? record.categoryName : (record.categoryName ? record.commonProblemCategoryId : ""),
              rules: [{
                required: true,
                message: messages('help-center-admin.key13')/*请选择分类*/
              }]
            })
            (<Select placeholder={messages('common.select')/*请选择*/}
                     disabled={disabled}
                     getPopupContainer={triggerNode => triggerNode.parentNode}>
              {categoryList.map(item => {
                return(
                  <Option key={item.id}>{item.name}</Option>
                )
              })}
            </Select>)
            }
          </FormItem>
          <FormItem {...formItemLayout} label={messages('help-center-admin.key14')/*分配角色*/}>
            <CheckboxGroup options={authorityOption} value={authorities} onChange={this.onAuthorityNamesChange} disabled={disabled}/>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('remark', {
              initialValue: record.remark,
              rules: [{
                required: false,
              }]
            })
            (<TextArea rows={6} placeholder={messages('common.please.input')/*请输入*/} maxLength={'200'} disabled={disabled}/>)
            }
          </FormItem>
        </Form>
        <Row style={{marginBottom: 100}}>
          <Col span={3} style={{textAlign: 'right', color: 'rgba(0, 0, 0, 0.85)', fontSize: 14}}>
            <span style={{color: 'red'}}>*&nbsp;</span>{messages('help-center-admin.key15')/*标题及正文*/}：
          </Col>
          <Col span={20} style={{marginTop: -10}}>
            <TitleAndContentI18n disabled={disabled}
                                 onI18nChange={this.onI18nChange}
                                 i18n={i18n}/>
          </Col>
        </Row>
        <div className={'question-maintenance-edit-btn'}>
          <Button type={'primary'}
                  style={{marginRight: 20}}
                  loading={loading}
                  onClick={this.handleSave}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </div>
      </div>
    )
  }
}

QuestionMaintenanceEdit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
  }
}

const wrappedQuestionMaintenanceEdit = Form.create()(QuestionMaintenanceEdit);
export default connect(mapStateToProps)(wrappedQuestionMaintenanceEdit);
